﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.PackageTypeCommand;
using D.Medicalcare.Write.API.Application.Commands.RegistrationCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.RegistrationHandler
{
    public class UpdateRegistrationHandler : IRequestHandler<UpdateRegistrationCommand, APIResult<Registration>>
    {
        private readonly IBaseRepository<Registration> rrep;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">映射</param>
        public UpdateRegistrationHandler(IBaseRepository<Registration> rrep, IMapper mapper)
        {
            this.rrep = rrep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 更新套餐类型
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">参数</param>
        /// <returns></returns>
        public async Task<APIResult<Registration>> Handle(UpdateRegistrationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<Registration> result = new APIResult<Registration>();

                var model = rrep.GetAll().FirstOrDefault(x => x.RegistrationId == request.RegistrationId);
                model.Statue = request.Statue;
                if (request.Statue == "已取消")
                {
                    model.UpdateTime = DateTime.Now;
                    model.UpdateReson = request.UpdateReson;
                }
               var a= rrep.Update(model).Result;

                if (a > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data =model;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "修改失败";
                    return await Task.FromResult(result);
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
